#include "header.h"

void *server(void *ptr)
{
	printf("SERVER THREAD CREATED\n");
	uint16_t myPort = (uint16_t)((int) ptr);
	

	int sockDesc;	
	int childSock = 0;
	struct sockaddr_in serverAddress, clientAddress;
	socklen_t clientAddressLength = sizeof(clientAddress);

	sockDesc = socket(AF_INET,SOCK_STREAM,0);										//Create socket
	if (sockDesc==-1)
	{
		perror("Create socket\n");
	}
	
	
	memset(&serverAddress,'\0',sizeof(serverAddress));
	serverAddress.sin_family = AF_INET;
	serverAddress.sin_addr.s_addr = INADDR_ANY;
	serverAddress.sin_port = htons(myPort);
	bind(sockDesc,(struct sockaddr *)&serverAddress,sizeof(serverAddress));					//Bind Socket

	listen(sockDesc,20);		

	pthread_t childThread[512];
	int noOfThreads = 0;

	struct timeval selectTimeOut;
	selectTimeOut.tv_sec = 1;
	selectTimeOut.tv_usec = 0; 
	
	fd_set readfds;
	
	int rv;

	while(1)
	{
		FD_ZERO(&readfds);
		FD_SET(sockDesc, &readfds);	
		
		rv = select(sockDesc+1, &readfds, NULL, NULL, &selectTimeOut);
		//printf("SERVER IS ALIVE\n");
		if(rv == -1) 
		{
			perror("select 1\n"); // error occurred in select()
			shutdownFlag = true;
			pthread_exit(NULL);
		}
		else if(rv == 0)
		{
			if(shutdownFlag == true || joinToTheNetworkFlag == true)
			{	
				
				pthread_mutex_lock(&ReadQueue);													//APPLY LOCK
				pthread_cond_signal(&condition_var_Read);	
				pthread_mutex_unlock(&ReadQueue);													//APPLY LOCK

				close(sockDesc);
				if(shutdownFlag == true)
				{
					printf("CommandLine Thread EXITED by SERVER\n");
					pthread_cancel(commandLineThread); 
				}
				printf("Server Thread EXIT due to Shutdown\n");
				pthread_exit(NULL);
			}
			continue;
		}

		memset(&clientAddress,'\0',sizeof(clientAddress));
		childSock = accept(sockDesc, (struct sockaddr *)&clientAddress,&clientAddressLength);
		printf("Accept = %d\n",childSock);
		if (childSock<0)
		{
			perror("Accept connection \n");
		}
		 
		iretChildThread = pthread_create(&childThread[(noOfThreads++)%512], NULL, child, (void *)childSock); 

	}
	return NULL;
}


